// 验证登录
const token = window.localStorage.getItem('token')
const id = window.localStorage.getItem('admin_id')
const goodsId = window.localStorage.getItem('goodsId')

if (!token || !id) {
  window.location.href = './login.html'
} else {
  // 请求商品评论
  getCommentList()
}

// 获取评论列表
function getCommentList() {
  // 发送请求
  $.ajax({
    url: 'http://localhost:8888/getComment/list',
    method: 'GET',
    data: { id:id,goodsId: goodsId,current: 1,pagesize: 12},
    headers: { authorization: token },
    success (res) {
      // 渲染页面
      bindHtml(res)
    }
  })
}
// 渲染页面
function bindHtml(res) {
  // 判断渲染 empty 标签还是 list 标签
  if (res.comment.length===0) {
    $('.empty').addClass('active')
    $('.display_list').removeClass('active')
    return
  }else{
  // 渲染页面
  let str = `
    <div class="top">
      <div>发表人</div>
      <div>留言</div>
      <div>发表时间</div>
      <div>操作</div>
    </div>
    <ul class="center">
    `

    res.comment.forEach(item => {
      str += `
        <li>
          <div class="username">
            ${ item.username }
          </div>
          <div class="comment">
            ${ item.content }
          </div>
          <div class="time">
            ${ item.time.substring(0,10)}&nbsp&nbsp${ item.time.substring(11,16)}
          </div>
          <div class="destory">
            <button commentId="${ item.comment_id }"class="del">删 除</button>
          </div>
      `
    })
    str+=`
        </li>
      </ul>
    `
   $('.display_list').html(str)
  }
}


// 删除评论
$('.display_list').on('click', '.center .del', function (e) {
  e.preventDefault()
  $.ajax({
    url: 'http://localhost:8888/getComment/remove',
    method: 'post',
    data: { commentId: $(this).attr('commentId')},
    headers: { authorization: token },
    success (res) {
      // 渲染页面
      console.log(res)
    }
  })
  window.location.reload()
  // 重新渲染页面
  getCommentList()
})
